package com.aiyige.page.player;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.TypedArray;
import android.graphics.Point;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Patterns;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.configs.MyConfig;
import com.aiyige.model.AiyigeExceptionModel;
import com.aiyige.page.my.settings.ConfigUltis;
import com.aiyige.page.player.presenter.GesturePresenter;
import com.aiyige.page.player.view.IPlayerView;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.AppUtils;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.aiyige.utils.crash.CrashUtils;
import com.pili.pldroid.player.AVOptions;
import com.pili.pldroid.player.PLMediaPlayer;
import com.pili.pldroid.player.PlayerState;
import com.pili.pldroid.player.widget.PLVideoTextureView;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.RxFileTool;
import com.vondear.rxtools.RxNetTool;

import java.util.ArrayList;
import java.util.List;

import static com.pili.pldroid.player.AVOptions.MEDIA_CODEC_HW_DECODE;

/**
 * 播放器集成
 * Created by xiachao on 2017/11/6.
 */
public class PlayerView extends FrameLayout implements IPlayerView {
    /**
     * 解码方式:
     * <li>codec＝AVOptions.MEDIA_CODEC_HW_DECODE，硬解</>
     * <li>codec=AVOptions.MEDIA_CODEC_SW_DECODE, 软解</li>
     * <li>codec=AVOptions.MEDIA_CODEC_AUTO, 硬解优先，失败后自动切换到软解<li/>
     */
//    private static final int mediaCodec = MEDIA_CODEC_AUTO;//优先硬件
    private static final int mediaCodec = MEDIA_CODEC_HW_DECODE;//硬件
    private static final String VIDEO_CACHE_DIR = MyConfig.VIDEO_CACHE_DIR;
    private int seekBarMax = 1000;
    boolean cache = true;
    boolean isLiveStreaming = false;//是否是直播
    boolean isLoop = false;
    Context mContext;
    ImageView converView;
    PLVideoTextureView mVideoView;
    PlayerFragment fragment = null;// 绑定activity的生命周期，用来控制播放器
    PlayerController mediaController;
    boolean isLandspace = false;
    RelativeLayout rlPlayer;
    FrameLayout playerParentView;
    GesturePresenter gesturePresenter;
    View loadingView;

    public PlayCallback getPlayCallback() {
        return playCallback;
    }

    public void setPlayCallback(PlayCallback playCallback) {
        this.playCallback = playCallback;
    }

    PlayCallback playCallback;
    // 播放控制
    private int playIndex = 0;

    private int playSpeed = PlaySpeed.SPEED_PERCENT_100;

    private ImageView ivBack;

    private View buyLayout;

    public List<PlayerInfo> getPlayList() {
        return playList;
    }

    boolean canPlayNotWifi = false;

    public void setCanPlayNotWifi(boolean canPlayNotWifi) {
        this.canPlayNotWifi = canPlayNotWifi;
    }

    public boolean isFullScreen() {
        return isFullScreen;
    }

    public boolean needPlayerController = true;

    public void setFullScreen(boolean fullScreen) {
        isFullScreen = fullScreen;
        setScreenRotate();
    }

    public boolean isFullScreen = false;

    @Override
    public PlayerInfo getCurrentPlayInfo() {
        if (!ListUtil.isEmpty(getPlayList())) {
            return getPlayList().get(playIndex);
        }
        return null;
    }

    public void setPlayList(List<PlayerInfo> playList) {
        this.playList = playList;
        if (mediaController != null) {
            mediaController.setVisibleMenu(!ListUtil.isEmpty(playList) && playList.size() > 1);
        }
    }

    private List<PlayerInfo> playList;

//    private int playIndex = 0;


    /**
     * 视频的方向
     */
    private int mVideoRotation;
    private boolean needResume;

//    private View backView;

    /**
     * 是否停止自动列表播放
     */
    private boolean stopLoopPlayback = false;


    public PlayerView(Context context) {
        super(context);
        this.mContext = context;
        init();
    }

    public PlayerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.AiyigePlayerView);
        needPlayerController = ta.getBoolean(R.styleable.AiyigePlayerView_need_player_controller, true);
        ta.recycle();
        init();
    }

    public PlayerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.AiyigePlayerView);
        needPlayerController = ta.getBoolean(R.styleable.AiyigePlayerView_need_player_controller, true);
        ta.recycle();
        init();
    }

    public void setPlayerParentView(FrameLayout playerParentView) {
        this.playerParentView = playerParentView;
    }

    boolean fillProgress = false;
    View rootView;

    public void init() {

        rootView = LayoutInflater.from(getContext()).inflate(R.layout.player, this, true);

        mVideoView = (PLVideoTextureView) rootView.findViewById(R.id.PLVideoTextureView);
        converView = (ImageView) rootView.findViewById(R.id.CoverView);
        mVideoView.setCoverView(converView);
        loadingView = rootView.findViewById(R.id.LoadingView);
        loadingView.setVisibility(View.VISIBLE);
        ImageView ivLoadView = (ImageView) rootView.findViewById(R.id.iv_loading);
        mVideoView.setBufferingIndicator(loadingView);
        mVideoView.setDisplayAspectRatio(PLVideoTextureView.ASPECT_RATIO_FIT_PARENT);
        ivBack = (ImageView) rootView.findViewById(R.id.iv_player_back);
        if (!needPlayerController) {
            ivBack.setVisibility(View.GONE);
            loadingView.setVisibility(View.GONE);
        }
        buyLayout = rootView.findViewById(R.id.buy_tips_layout);
        TextView tvBuy = (TextView) rootView.findViewById(R.id.btn_buy);
        tvBuy.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (playCallback != null) {
                    playCallback.buy();
                }
            }
        });
        // 1 -> hw codec enable, 0 -> disable [recommended]
        int codec = mediaCodec;
        AVOptions options = new AVOptions();
        // the unit of timeout is ms
        options.setInteger(AVOptions.KEY_PREPARE_TIMEOUT, 10 * 1000);
        options.setInteger(AVOptions.KEY_LIVE_STREAMING, false ? 1 : 0);
        // 1 -> hw codec enable, 0 -> disable [recommended]
        options.setInteger(AVOptions.KEY_MEDIACODEC, codec);
        if (cache) {
            options.setString(AVOptions.KEY_CACHE_DIR, VIDEO_CACHE_DIR);
        }
        mVideoView.setAVOptions(options);
        mVideoView.setDebugLoggingEnabled(BuildConfig.DEBUG);

        mVideoView.setOnInfoListener(new PLMediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(PLMediaPlayer plMediaPlayer, int i, int i1) {
                if (!fillProgress && plMediaPlayer.isPlaying()) {
                    fillProgress = true;
                    mediaController.showWidget();
                    Log.i("", "refreshPlayer-onInfo()");
                    if (needPlayerController) {
                        if (gesturePresenter == null) {
                            gesturePresenter = new GesturePresenter(mContext, PlayerView.this, mediaController);
                        }
                    }
                }
                return false;
            }
        });
        mVideoView.setOnVideoSizeChangedListener(new PLMediaPlayer.OnVideoSizeChangedListener() {
            @Override
            public void onVideoSizeChanged(PLMediaPlayer plMediaPlayer, int i, int i1) {
                Log.i("player", "onVideoSizeChanged==" + plMediaPlayer);
            }
        });
        mVideoView.setOnBufferingUpdateListener(new PLMediaPlayer.OnBufferingUpdateListener() {
            @Override
            public void onBufferingUpdate(PLMediaPlayer plMediaPlayer, int i) {
                Log.i("player", "onBufferingUpdate==" + plMediaPlayer);
            }
        });
        mVideoView.setOnCompletionListener(new PLMediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(PLMediaPlayer plMediaPlayer) {
                if (mediaController != null) {
                    mediaController.showWidget();
                }
                if (isStopLoopPlayback()) {//用户手动选择在了某一集，则停止自动播放下一集
                    return;
                }
                Log.i("player", "onCompletion==" + plMediaPlayer);
                if (getPlayList() != null && !getPlayList().isEmpty()) {
                    int nextIndex = playIndex + 1;
                    boolean isLast = getPlayList().size() == nextIndex;
                    if (!isLast) {
                        play(nextIndex);
                    }
                }

                if (getPlayCallback() != null) {
                    getPlayCallback().onComplete();
                }

            }
        });
        mVideoView.setOnErrorListener(new PLMediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(PLMediaPlayer plMediaPlayer, int i) {
                if (i == -3) {//播放器会自动重连，所以不用提醒
//                    ToastX.show("网络异常");
                    return false;
                }
                String errorString = JsonUtil.toString(getCurrentPlayInfo());
                if (i == -2) {//地址无效导致的错误提示
                    CrashUtils.getInstance().netSubmitLog(AiyigeExceptionModel.type_video_player, "errorCode:"+i+" 播放地址无效？"+errorString, AiyigeExceptionModel.rating_4);
                    if (getPlayCallback() != null) {
                        getPlayCallback().onError(i, mContext.getString(R.string.play_path_invalid) + "\n" + errorString);
                    } else {
                        ToastX.show(mContext.getString(R.string.play_path_invalid));
                    }

                } else {
                    CrashUtils.getInstance().netSubmitLog(AiyigeExceptionModel.type_video_player, "errorCode:"+i+" "+errorString, AiyigeExceptionModel.rating_2);
                    if (getPlayCallback() != null) {
                        getPlayCallback().onError(i, "其他错误：\n" + errorString);
                    }
                }
                Log.i("player", "onError==" + plMediaPlayer + " errorCode=" + i);
                return false;
            }
        });
        mVideoView.setOnPreparedListener(new PLMediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(PLMediaPlayer plMediaPlayer, int i) {
                Log.i("player", "onPrepared==" + plMediaPlayer);
//                setPlayer(plMediaPlayer);
            }
        });
        ivBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mVideoView.setLooping(isLoop);
        rlPlayer = (RelativeLayout) findViewById(R.id.rl_player_view);
        mediaController = new PlayerController(mContext, this, !false, false);
        mediaController.setiPlayerView(this);
//        mediaController.setOnClickSpeedAdjustListener(mOnClickSpeedAdjustListener);
        // 广告播放的时候 不需要控制
        if (needPlayerController) {
            mVideoView.setMediaController(mediaController);
//        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mediaController.getLayoutParams();
//        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            rlPlayer.post(new Runnable() {
                @Override
                public void run() {
                    rlPlayer.addView(mediaController);
                }
            });
        }
        mVideoView.setScreenOnWhilePlaying(true);//保持屏幕常亮
        if (fragment == null) {
            fragment = new PlayerFragment(this);
            try {
                getActivity().getSupportFragmentManager().beginTransaction().add(fragment, "player").commitAllowingStateLoss();
            } catch (Exception e) {
                String error = e.toString();
                Log.e("playerError", "=======" + error);
            }
        }
    }

    public void doBack() {
        Activity activity = RxActivityTool.currentActivity();
        if (activity instanceof PlayerPage) {
            RxActivityTool.finishActivity(activity);
            return;
        }
        if (isLandspace) {
            setScreenRotate();
        } else {
            getActivity().finish();
        }
    }

    /**
     * 单视频播放
     *
     * @param videoPath
     */
    public void start(String videoPath) {
        if (TextUtils.isEmpty(videoPath) || !Patterns.WEB_URL.matcher(videoPath).matches()) {
            ToastX.show(mContext.getString(R.string.play_path_invalid));
            return;
        }
        if (playList == null) {
            playList = new ArrayList<>();
        }
        playList.clear();
        playList.add(new PlayerInfo(videoPath, videoPath, "", true));
        setPlayList(playList);
        play(playIndex);
    }

    /**
     * 列表播放
     *
     * @param playList
     * @param index
     */
    public void start(List<PlayerInfo> playList, int index) {
        setPlayList(playList);
        play(index);
    }

    public void start(List<PlayerInfo> playList, int index, long seekTo) {
        setPlayList(playList);
        play(index, seekTo);
    }

    /**
     * 选择单集播放
     *
     * @param index
     */
    public void play(int index) {
        play(index, 0);
    }

    /**
     * 选择并快进到
     *
     * @param index
     * @param seekTo
     */
    public void play(final int index, final long seekTo) {
        if (getPlayList() == null || getPlayList().isEmpty()
                || (getPlayList().size() - 1) < index) {
            return;
        }
        if (mVideoView.isPlaying() && index == playIndex) {
            return;
        }
        playIndex = index;
        if (getPlayList().size() == 1 && index == 1) {
            // 如果播放列表只有1，自动播放第一个
            playIndex = 0;
        }
        final PlayerInfo playerInfo = getPlayList().get(playIndex);
        // 检查是否是本地视频，以及文件是否存在
        if (!TextUtils.isEmpty(playerInfo.getPath()) && !playerInfo.getPath().startsWith("http") && !RxFileTool.fileExists(playerInfo.getPath())) {
            if (getPlayCallback() != null) {
                getPlayCallback().onError(0, "");
            } else {
                ToastX.show(mContext.getString(R.string.local_video_is_not_exist));
            }
            return;
        }
        // 检查通过或用户点击继续播放则可以播放
        Callback checkCallback = new Callback() {
            @Override
            public void call() {
                loadingView.setVisibility(View.VISIBLE);

                mVideoView.setVideoPath(playerInfo.getPath());
//                mVideoView.setVideoPath("http://rs.everygod.com/video/ff80808163343a5a016338a12e1d0109_1525664342969_2220dba579294c9e862b3b9feb6b3216.mp4");

                mVideoView.setOnPreparedListener(new PLMediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(PLMediaPlayer plMediaPlayer, int i) {
                        if (getPlayCallback() != null) {// 给页面刷新当前选集
                            getPlayCallback().onPlaying();
                        }
//                        resetPlayerControllerViews();
                        setVideoScreenOrientation();
//                        if (isVerticalVideo()) {// 竖屏全屏的视频
//                            if (getPlayCallback() != null) {
//                                getPlayCallback().orientation(!isLandspace);
//                            }
//                        }
                        if (seekTo > 1) {
                            mediaController.seekTo(seekTo);
                        }//因为异步初始化，比如要用监听再开始
                        // 当页面不可见，则不播放（比如支付完成的时候，页面后台刷新，但不播放）
                        if (mContext != null && !AppUtils.isForeground(mContext, mContext.getClass().getName())) {
                            return;
                        } else {
                            mVideoView.start();
                        }

                    }
                });
            }
        };
        checkPlayInfo(playerInfo, checkCallback);
        if (getPlayCallback() != null) {// 给页面刷新当前选集
            getPlayCallback().playChange(playIndex);
        }
        mediaController.onNext();
        mediaController.clearABPosition();
    }

    private void resetPlayerControllerViews() {
        orientationChange(isLandspace);
    }

    public void resumePlay(long time) {
        if (mVideoView != null && (mVideoView.getPlayerState() == PlayerState.DESTROYED || mVideoView.getPlayerState() == PlayerState.PREPARED)) {
            play(getPlayIndex(), time);
        }
    }

    public boolean checkPlayInfo(PlayerInfo playerInfo, Callback callback) {
        if (!playerInfo.isFree()) {
            ivBack.setVisibility(View.VISIBLE);
            stopPlayback();
            buyLayout.setVisibility(View.VISIBLE);
            mediaController.onNext();
            if (isLandspace) {//全屏状态下遇到收费视频，返回到竖屏状态，执行返回按钮
                doBack();
            }
            return false;
        } else {
            buyLayout.setVisibility(View.GONE);
            ivBack.setVisibility(View.INVISIBLE);
        }
        if (TextUtils.isEmpty(playerInfo.getPath())) {
            if (isPlaying()) {
                mVideoView.stopPlayback();//和ios保持一致,只要切换地址就中断之前的播放
            }
            ToastX.show(getActivity().getResources().getString(R.string.play_path_invalid));
            return false;
        }
        // 本地视频检查，并检查文件是否存在
        if (!playerInfo.getPath().startsWith("http")) {

            if (RxFileTool.fileExists(playerInfo.getPath())) {
                callback.call();
            } else {
                ToastX.show(mContext.getString(R.string.play_path_file_not_exist));
            }
        } else {
            boolean checkUrl = Patterns.WEB_URL.matcher(playerInfo.getPath()).matches();
            if (!checkUrl) {
                ToastX.show(mContext.getString(R.string.play_path_invalid));
                return false;
            }
        }
        // 本地视频 隐藏下载按钮
        if (mediaController != null) {
            mediaController.setVisibleDownload(!playerInfo.isLocalVideoAndExist());
//            mediaController.setVisibleMenu(!playerInfo.isLocalVideoAndExist());
        }
        //已经是WIFI环境 或者 用户手动点击 允许非wifi环境下播放  或者 用户把流量提醒开关关闭（app安装后是默认打开）
        if (RxNetTool.isWifiConnected(mContext) || canPlayNotWifi || checkNoWifiPlay(callback)) {
            callback.call();
            return true;
        } else {
            return false;
        }

    }

    public boolean checkNoWifiPlay(final Callback callback) {
        PlayerInfo playerInfo = getCurrentPlayInfo();
        if (playerInfo != null && !TextUtils.isEmpty(playerInfo.getPath()) && !playerInfo.getPath().startsWith("http") && RxFileTool.fileExists(playerInfo.getPath())) {
            return true;
        }
        boolean isGprsNotification = ConfigUltis.isEnableGprsNotification();
        if (isGprsNotification && AccountUtil.isWIFIRemind()) {// 默认提醒，但是用户点了不提醒，但时间过了第二天，也要提醒
            new AlertDialog.Builder(mContext).setTitle(R.string.no_wifi_remind)
                    .setPositiveButton(R.string.go_on, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            canPlayNotWifi = true;
                            AccountUtil.setWIFIRemindTime();
                            dialog.dismiss();
                            callback.call();//继续播放
                        }
                    })
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
            return false;
        } else {
            callback.call();//继续播放
            return true;
        }
    }

    /**
     * 当前是否正在显示 购买 布局（表示这个视频需要购买）
     * 其他操作应该不可以触发
     *
     * @return
     */
    public boolean buyLayoutShowing() {
        return buyLayout != null && buyLayout.getVisibility() == View.VISIBLE;
    }

    public void setVolume(float v) {
        mVideoView.setVolume(v, v);
    }


    /**
     * PlaySpeed
     * SPEED_PERCENT_20
     * SPEED_PERCENT_40
     * SPEED_PERCENT_60
     * SPEED_PERCENT_80
     * SPEED_PERCENT_100
     * SPEED_PERCENT_150
     * SPEED_PERCENT_200
     *
     * @param i
     * @return
     */
    public boolean setPlaySpeed(int i) {
        return mVideoView.setPlaySpeed(i);
    }

    private FragmentActivity getActivity() {
        return ((FragmentActivity) mContext);
    }


    public boolean isLandspace() {
        return isLandspace;
    }

    public void setScreenRotate() {
        if (isVerticalVideo()) {// 竖屏全屏的视频
            if (getPlayCallback() != null) {
                getPlayCallback().orientation(!isLandspace);
            }
        } else {
            if (!isLandspace) {
                getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            } else {
                getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        }
    }


    /**
     * 通过视频宽高判断 是否是竖屏视频
     *
     * @return
     */
    public boolean isVerticalVideo() {
        return mVideoView != null && mVideoView.getHeight() > mVideoView.getWidth();
    }


    public void setMirror(boolean mirror) {
        mVideoView.setMirror(mirror);
    }

    public void onBackPressed() {
        if (mediaController != null) {
            mediaController.doBack();
        }
    }

    @Override
    public String getTitle() {
        if (!ListUtil.isEmpty(getPlayList())) {
            return getPlayList().get(playIndex).getTitle();
        }
        return null;
    }

    public interface PlayCallback {
        void playChange(int position);

        void buy();

        void orientation(boolean landscape);

        void downloadVideos();

        void onPlaying();

        void onComplete();

        void onError(int errorCode, String errorDetail);
    }


    public int getPlayIndex() {
        return playIndex;
    }

    public boolean isPlaying() {
        if (mVideoView == null) {
            return false;
        }
        return mVideoView.isPlaying();
    }

    public long getCurrentPosition() {
        if (mVideoView == null) {
            return 0;
        }
        return mVideoView.getCurrentPosition();
    }

    public boolean canPause() {
        if (mVideoView == null) {
            return false;
        }
        return mVideoView.canPause();
    }

    public void pause() {
        mVideoView.pause();
        if (mediaController != null) {
            mediaController.updatePausePlay();
        }
    }

    public void stopPlayback() {
        if (mVideoView != null) {
            mVideoView.stopPlayback();
        }
    }

    public PlayerState getPlayerState() {
        if (mVideoView != null) {
            return mVideoView.getPlayerState();
        }
        return PlayerState.IDLE;
    }

    public void download() {
        if (playCallback != null) {
            playCallback.downloadVideos();
        }
    }

    /**
     * 播放检查回调
     */
    interface Callback {
        void call();
    }

    /**
     * 是否停止循环播放
     *
     * @return
     */
    public boolean isStopLoopPlayback() {
        return stopLoopPlayback;
    }

    /**
     * 停止循环播放
     *
     * @param stopLoopPlayback
     */
    public void setStopLoopPlayback(boolean stopLoopPlayback) {
        this.stopLoopPlayback = stopLoopPlayback;
    }


    private boolean isFree() {
        PlayerInfo playerInfo = getCurrentPlayInfo();
        return playerInfo != null && playerInfo.isFree();
    }

    public boolean isLocalVideo() {
        return getCurrentPlayInfo() != null && getCurrentPlayInfo().isLocalVideoAndExist();
    }

    private void setVideoScreenOrientation() {
        if (isVerticalVideo() && mContext != null && mContext instanceof Activity) {
            ((Activity) mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
//        else {
//            if (isLandspace()) {
//                ((Activity) mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
//            }
//        }
    }


    public void orientationChange(boolean landscape) {
        if (!needPlayerController) {
            return;
        }
        isLandspace = landscape;
//        if (isVerticalVideo() && mVideoView != null) {
//            mediaController.setRotation();
//        }
        if (playerParentView != null) {
            Display display = ((Activity) mContext).getWindowManager().getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) playerParentView.getLayoutParams();
            layoutParams.width = LayoutParams.MATCH_PARENT;
            layoutParams.height = isLandspace ? LayoutParams.MATCH_PARENT : UIHelper.dip2px(mContext, 203);
            playerParentView.setLayoutParams(layoutParams);
        }
        mediaController.setScreenRotate(isLandspace);

        mediaController.fixLandspace();

//        if (landscape && !isFree()) {
//            ivBack.setVisibility(View.VISIBLE);
//        } else {
//            ivBack.setVisibility(View.INVISIBLE);
//        }
    }

    public long getLastPlayPosition() {
        if (fragment != null) {
            return fragment.lastPlayTime;
        } else {
            return 0;
        }
    }


    public boolean isLock() {
        return mediaController != null ? mediaController.isLock() : false;
    }

    public void seekTo(long seekTo) {
//        pause();
        if (mediaController != null) {
            mediaController.seekTo(seekTo);
        }
    }

    public void setOnSeekCompleteListener(PLMediaPlayer.OnSeekCompleteListener onSeekCompleteListener) {
        if (mVideoView != null) {
            mVideoView.setOnSeekCompleteListener(onSeekCompleteListener);
        }
    }

    // 因主持人变动（例如 进度变动）
    private boolean isPresenterChanged = false;

    public boolean isPresenterChanged() {
        return isPresenterChanged;
    }

    public void setPresenterChanged(boolean presenterChanged) {
        isPresenterChanged = presenterChanged;
    }


    public void syncSuccess() {
        setVolume(1);
    }

    public void syncFaild() {
        setVolume(0);
    }

}
